package com.size.mall.payment.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.size.mall.config.annotations.LoginRequired;
import com.size.mall.mallapi.entity.OmsOrder;
import com.size.mall.mallapi.entity.PaymentInfo;
import com.size.mall.mallapi.service.OrderService;
import com.size.mall.mallapi.service.PaymentInfoService;
import com.size.mall.payment.config.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

import java.math.BigDecimal;
import java.nio.channels.FileChannel;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static cn.hutool.core.lang.Console.*;
import static cn.hutool.core.util.StrUtil.isNotBlank;
import static java.lang.System.out;

@Controller
public class PaymentController {



    @Autowired
    AlipayClient alipayClient;

    @Autowired
    PaymentInfoService paymentService;

    @Reference
    OrderService orderService;



    @RequestMapping("alipay/callback/return")
    @LoginRequired(loginSuccess = true)
    public String aliPayCallBackReturn(HttpServletRequest request, ModelMap modelMap){
        // 回调请求中获取支付宝参数
        String sign = request.getParameter("sign");
        String trade_no = request.getParameter("trade_no");
        String out_trade_no = request.getParameter("out_trade_no");
        String trade_status = request.getParameter("trade_status");
        String total_amount = request.getParameter("total_amount");
        String subject = request.getParameter("subject");
        String call_back_content = request.getQueryString();


        // 通过支付宝的paramsMap进行签名验证，2.0版本的接口将paramsMap参数去掉了，导致同步请求没法验签
        if(isNotBlank(sign)){
            // 验签成功
            // 更新用户的支付状态

            PaymentInfo paymentInfo = new PaymentInfo();
            paymentInfo.setOrderSn(out_trade_no);
            paymentInfo.setPaymentStatus("已支付");
            paymentInfo.setAlipayTradeNo(trade_no);// 支付宝的交易凭证号
            paymentInfo.setCallbackContent(call_back_content);//回调请求字符串
            paymentInfo.setCallbackTime(new Date());

            // 根据外部交易号更新内容

            paymentService.updatePayment(paymentInfo);

        }



        // 更新用户的支付状态
        return "finish";
    }


    @RequestMapping("alipay/submit")
    @LoginRequired(loginSuccess = true)
    @ResponseBody
    public String alipay(String outTradeNo, BigDecimal totalAmount, HttpServletRequest request, ModelMap modelMap) {

        String form = null;

        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_payment_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url);

        //region 封装参数param
        Map<String,Object> map = new HashMap<>();
        map.put("out_trade_no",outTradeNo);
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        map.put("total_amount",0.01);
        map.put("subject","尚硅谷感光徕卡Pro300瞎命名系列手机");

        String param = JSON.toJSONString(map);
        //endregion

        alipayRequest.setBizContent(param);




        // 获得一个支付宝请求的客户端的链接
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); // 生成sdk表单

            log(form);



        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        // 生成并保存用户信息


        OmsOrder omsOrder = orderService.getOrderByOrderTradeNo(outTradeNo);
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setCreateTime(new Date())
                   .setOrderId(omsOrder.getId())
                   .setOrderSn(omsOrder.getOrderSn())
                   .setPaymentStatus("未付款")
                   .setSubject("小山城商品一件")
                   .setTotalAmount(totalAmount);

        paymentService.save(paymentInfo);



        // 提交表单到支付宝
        return form;

    }


    /**
     *  订单模块调用,生成交易价格
     *  有用信息 总价 外部单号
     *
     *
     * @param totalAmount
     * @param outTradeNo
     * @param request
     * @param modelMap
     * @return
     */
    @GetMapping("index")
    @LoginRequired
    public String index(String totalAmount, String
                                    outTradeNo, HttpServletRequest request
                        , ModelMap modelMap
                        ) {

        String memberId = (String) request.getAttribute("memberId");
        String nickname = (String) request.getAttribute("nickname");

        modelMap.put("totalAmount", totalAmount);
        modelMap.put("outTradeNo", outTradeNo);
        modelMap.put("nickname", nickname);





        return "index";
    }


    @RequestMapping("mx/submit")
    @LoginRequired(loginSuccess = true)
    public String mx(String outTradeNo, BigDecimal totalAmount, HttpServletRequest request, ModelMap modelMap){


        return null;
    }


}
